/**
 * @author: Loy-winters1224@163.com
 * @date: 2014-8-21-下午6:38:19
 */
package net.loyintean.pearlshell.wechat.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @author Loy-winters1224@163.com
 * @version 2014-8-21.1.0.0
 */
public class EncrAESUtil {

	/**
	 * 加密
	 * 
	 * @param encryptStr
	 * @return
	 */
	private static byte[] encrypt(byte[] src, String key) throws Exception {
		Cipher cipher = Cipher.getInstance("AES");
		SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), "AES");
		cipher.init(Cipher.ENCRYPT_MODE, securekey);// 设置密钥和加密形式
		return cipher.doFinal(src);
	}

	/**
	 * 二行制转十六进制字符串
	 * 
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toUpperCase();
	}

	private static final String ensureKeyLength(String crypt_key) {
		assert crypt_key != null;

		StringBuilder key_16 = new StringBuilder(crypt_key);

		if (key_16.length() > 16) {
			while (key_16.length() > 16) {
				key_16.deleteCharAt(key_16.length() - 1);
			}
		} else if (key_16.length() < 16) {
			while (key_16.length() < 16) {
				key_16.append("0");
			}
		}

		return key_16.toString();

	}

	/**
	 * 加密
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public final static String encrypt(String data, String crypt_key) {

		String key16Byte = ensureKeyLength(crypt_key);
		try {
			return byte2hex(encrypt(data.getBytes(), key16Byte));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
